import { Course, mockCourses } from '../model/Course';

// 课程服务类，负责处理课程相关的业务逻辑
export class CourseService {
  // 获取所有课程
  getAllCourses(): Promise<Course[]> {
    // 模拟异步获取数据
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve([...mockCourses]);
      }, 500);
    });
  }

  // 根据ID获取课程详情
  getCourseById(id: number): Promise<Course | undefined> {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(mockCourses.find(course => course.id === id));
      }, 300);
    });
  }

  // 根据标签筛选课程
  getCoursesByTag(tag: string): Promise<Course[]> {
    return new Promise((resolve) => {
      setTimeout(() => {
        const filtered = mockCourses.filter(course => 
          course.tags.some(t => t.toLowerCase().includes(tag.toLowerCase()))
        );
        resolve(filtered);
      }, 400);
    });
  }

  // 搜索课程
  searchCourses(query: string): Promise<Course[]> {
    return new Promise((resolve) => {
      setTimeout(() => {
        const lowerQuery = query.toLowerCase();
        const results = mockCourses.filter(course => 
          course.title.toLowerCase().includes(lowerQuery) ||
          course.description.toLowerCase().includes(lowerQuery) ||
          course.instructor.toLowerCase().includes(lowerQuery)
        );
        resolve(results);
      }, 450);
    });
  }

  // 排序课程
  sortCourses(courses: Course[], sortBy: 'rating' | 'enrolledStudents' | 'credits', order: 'asc' | 'desc' = 'desc'): Course[] {
    const sorted = [...courses].sort((a, b) => {
      if (order === 'asc') {
        return a[sortBy] - b[sortBy];
      } else {
        return b[sortBy] - a[sortBy];
      }
    });
    return sorted;
  }

  // 计算平均评分
  calculateAverageRating(courses: Course[]): number {
    if (courses.length === 0) return 0;
    const sum = courses.reduce((total, course) => total + course.rating, 0);
    return Math.round((sum / courses.length) * 10) / 10;
  }

  // 获取热门课程（按报名人数排序）
  getPopularCourses(limit: number = 3): Promise<Course[]> {
    return this.getAllCourses().then(courses => {
      return this.sortCourses(courses, 'enrolledStudents').slice(0, limit);
    });
  }
}